"""
导出服务：协调仓储与策略
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, Type

from sqlalchemy.orm import Session

from ..domain import ProjectSnapshot
from ..repository import ProjectRepository, ProjectNotFoundError
from ..enums import IOFormat
from ..strategies.base import ExportStrategy, ExportResult
from ..strategies.json_strategy import JsonExportStrategy
from ..strategies.markdown_strategy import MarkdownExportStrategy
from ..strategies.word_strategy import WordExportStrategy
from ..strategies.excel_strategy import ExcelExportStrategy


class UnknownExportFormatError(RuntimeError):
    """不支持的导出格式"""


EXPORT_STRATEGIES: Dict[IOFormat, Type[ExportStrategy]] = {
    IOFormat.JSON: JsonExportStrategy,
    IOFormat.MARKDOWN: MarkdownExportStrategy,
    IOFormat.WORD: WordExportStrategy,
    IOFormat.EXCEL: ExcelExportStrategy,
}


@dataclass
class ExportResponse:
    snapshot: ProjectSnapshot
    result: ExportResult


class ProjectExporter:
    """导出器，通过策略扩展不同格式"""

    def __init__(self, db: Session):
        self.repository = ProjectRepository(db)

    def export(self, project_name_en: str, format_: IOFormat) -> ExportResponse:
        snapshot = self.repository.load_by_name_en(project_name_en)
        strategy_cls = EXPORT_STRATEGIES.get(format_)
        if not strategy_cls:
            raise UnknownExportFormatError(f"不支持的导出格式: {format_.value}")
        strategy = strategy_cls()
        result = strategy.export(snapshot)
        return ExportResponse(snapshot=snapshot, result=result)

    # 暴露仓储异常，便于路由层区分
    ProjectNotFoundError = ProjectNotFoundError

